//
//  ConfigManager.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/12.
//

import Foundation

var configManager = ConfigManager()
class ConfigManager : BaseViewModel {
    private let userDefaults = UserDefaults.standard
    private let userKey = "configKey"
    @Published var config : ConfigBean? {
        didSet {
            if let serverConfig = config?.serverConfig {
                QiniuUtils.accessKey = serverConfig.qiniu_access_key ?? ""
                QiniuUtils.secretKey = serverConfig.qiniu_secret_key ?? ""
                QiniuUtils.bucket = serverConfig.qiniu_bucket ?? ""
                QiniuUtils.host = serverConfig.qiniu_host ?? ""
            }
            //保存本地数据
            saveConfig()
            BackupsManager.shared.doRead()
        }
    }
    
    //保存本地数据
    private func saveConfig() {
        if let config = config {
            let encoder = JSONEncoder()
            if let encodedData = try? encoder.encode(config) {
                userDefaults.set(encodedData, forKey: userKey)
            }
        } else {
            userDefaults.removeObject(forKey: userKey)
        }
    }
    
    //加载本地数据
    private func loadConfig() -> ConfigBean? {
        if let encodedData = userDefaults.data(forKey: userKey),
           let decodedUser = try? JSONDecoder().decode(ConfigBean.self, from: encodedData) {
            return decodedUser
        }
        return nil
    }
    
    
    func getConfig() -> ConfigBean {
        return config ?? ConfigBean()
    }
}
